import uvicorn
from fastapi import FastAPI, HTTPException, Request, Body, Query 
from DAL import DbConnect
from Model.ResponseMode import ParamDetail,ClientHisParam,ClientHisResponse,GetlientHisInfoResponse
import pandas as pd 

app = FastAPI()

@app.get('/')
def GetMain():
    return "Service OK,Api Version 1.0"

@app.get('/GetClientHis')  
def GetClientHis(day: str = Query(None, title="Day", description="The day for which to retrieve history, in YYYY-MM-DD format"),
                 cname:str = Query(None, title="cname"),
                 ccom:str = Query(None, title="ccom")):  
    result = GetlientHisInfoResponse()
    if day is None:  
        # 如果 day 没有被提供，则使用默认日期（今天）  
        day = DbConnect.GetDefaultDay()
    search = ClientHisParam()  
    search.ClientName = cname
    search.ComName = ccom
    search.Day = day
    # 在这里使用 day 变量进行你的逻辑处理  
    result.Data = DbConnect.SearchClientHis(search)
    result.Code = 200
    result.Msg = "Successful"
    return result


#创建或更新数据
@app.post("/GenKey")  
async def GenKey(item: ClientHisParam = Body(...)):
    if item.ClientName == '' or item.ComName == '' or item.Day == '':
        raise HTTPException(status_code=417 , detail="Request Body Error")  
    key = DbConnect.DesEncrypt(f'{item.ComName}{item.ClientName}{item.Day}')
    result = ParamDetail()
    result.Key = key
    return result

#创建或更新数据
@app.post("/CreateClientHis")  
async def CreateItem(request: Request,item: ClientHisParam = Body(...)):
    result = ClientHisResponse()
    if item.ClientName == '' or item.ComName == '' or item.Day == '':
        result.Code = 417
        result.Msg = "Request Body Error"
        return result
    authorization = request.headers.get("Authorization")  
    if not authorization:  
        result.Code = 401
        result.Msg = "Authorization header is missing"
        return result
    key = DbConnect.DesEncrypt(f'{item.ComName}{item.ClientName}{item.Day}')
    if authorization != key:  
        result.Code = 401
        result.Msg = "Authorization header is wrong"
        return result
    result.Id = DbConnect.CreateClientHis(item)
    result.Code = 200
    result.Msg = "Successful"
    return result

#如果是想在Pycharm等IDE中直接运行，可以在代码中加入
#if __name__ == "__main__":
#   uvicorn.run(app, host='0.0.0.0', port=8010, reload=True)


